﻿using System;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Xml;
using NLog;
using OBoobsWallpaper.Configuration;
using OBoobsWallpaper.Entity;

namespace OBoobsWallpaper.Logic
{
    public interface IRssLoader
    {
        Rss LoadRss();
    }

    public class OBoobsRssLoader : IRssLoader
    {
        private readonly IRssLoaderConfig config;
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        public OBoobsRssLoader(IRssLoaderConfig config)
        {
            this.config = config;
        }

        private static string GetLinkFromId(string id)
        {
            return string.Format("http://media.oboobs.ru/boobs/0{0}.jpg", id.Substring(19, 4));
        }

        public Rss LoadRss()
        {
            XmlReader reader;
            try
            {
                reader = XmlReader.Create(config.Url);
            }
            catch (Exception ex)
            {
                throw new BException(ex, "Can not download rss from url:{0}", config.Url);
            }
            
            var atom = new Atom10FeedFormatter();
            if (!atom.CanRead(reader))
                throw new BException("Can not parse rss xml");

            atom.ReadFrom(reader);
            reader.Close();

            var rssItems = (from item in atom.Feed.Items.OfType<SyndicationItem>()
                            select
                                new RssItem
                                    {
                                        Id = item.Id,
                                        Title = item.Title.Text,
                                        ImageLink = GetLinkFromId(item.Id),
                                    }).ToList();
            Logger.Trace("{0} records loaded from {1}", rssItems.Count, config.Url);

            var rss = new Rss(atom.Feed.LastUpdatedTime.DateTime, rssItems);

            return rss;
        }
    }
}